package dep

import (
	"gitee.com/xuyiping_admin/pkg/cron"
	prom "github.com/prometheus/client_golang/prometheus"
	"go.uber.org/dig"
	"kpt-dtm/config"
	"kpt-dtm/module/dtm"
)

var DataCenterCrontabCounterVec = prom.NewCounterVec(
	prom.CounterOpts{
		Namespace: "kpt-dtm",
		Subsystem: "data_center",
		Name:      "crontab",
	},
	[]string{"name"},
)

// CrontabDependency 依赖注入结构体
type CrontabDependency struct {
	dig.In

	CrontabHub dtm.StoreEntry // 定时任务
}

func CommonCrontab() (out *cron.Crontab) {
	container := DI()
	if err := container.Provide(EntryCrontab); err != nil {
		panic(err)
	}
	if err := container.Invoke(func(c *cron.Crontab) { out = c }); err != nil {
		panic(err)
	}
	return
}

// EntryCrontab 直接创建定时任务，避免依赖注入的复杂性
func EntryCrontab(dependency CrontabDependency) *cron.Crontab {
	cfg := config.Options()
	cs := cfg.CronSetting

	crontab := cron.NewCrontab(DataCenterCrontabCounterVec)

	// 绑定定时任务
	err := crontab.Bind("data_init", cs.DtmInit, dependency.CrontabHub.DataHandle)
	if err != nil {
		panic(err)
	}

	err = crontab.Bind("data_retry", cs.DtmRetry, dependency.CrontabHub.DataHandle)
	if err != nil {
		panic(err)
	}

	return crontab
}
